import * as shpUtil from "shp-geojson";
import { ref } from "vue";
import { showFailToast } from "vant";

export function useUpload() {
  const fileLoading = ref(false);
  let file: File;
  let fileName: string;

  const onFileChange = async (f: any) => {
    file = f;
    fileName = f.name.replace(".zip", "");
  };

  const getArrayBuffer = (f: File) => {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsArrayBuffer(f);
      reader.onload = (e) => {
        const buffer = e.target!.result;
        resolve(buffer);
      };
    });
  };

  const getGeoJson = async (format: string) => {
    return new Promise(async (resolve) => {
      if (!file) {
        showFailToast("请上传文件！");
        resolve(null);
      } else {
        fileLoading.value = true;
        const buffer: any = await getArrayBuffer(file);
        shpUtil.toGeoJSON(buffer, null, format).then((json: any) => {
          resolve(json);
          fileLoading.value = false;
        });
      }
    });
  };

  return {
    onFileChange,
    getGeoJson,
    fileLoading,
  };
}
